package com.warmlight.voicepacket.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.AllPlayerAcitivity;
import com.warmlight.voicepacket.PlayDeatalActivity;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.data.PlaydeatalData;
import com.warmlight.voicepacket.data.RecommendData;
import com.warmlight.voicepacket.data.eventbus.ShareUnlock;
import com.warmlight.voicepacket.db.VoicePacketDBHelper;
import com.warmlight.voicepacket.fragment.CustomBottomSheetDialogFragment;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.utils.ClickLog;
import com.warmlight.voicepacket.utils.GlideCornerTransform;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.Call;


/**
 * 发现页面 推荐播单的adapter
 * Created by jason on 2018/6/5.
 */

public class RecommendRVAdapter extends RecyclerView.Adapter<RecommendRVAdapter.ViewHolder> {

    private Context mContext;
    private List<RecommendData.DataBean.PlayCoversBean> mList;
    private String category_id;

    public RecommendRVAdapter(Context context, List<RecommendData.DataBean.PlayCoversBean> list){
        mContext = context;
        mList = list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_recommend_header, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);

        viewHolder.iv_header_bg = (ImageView) view.findViewById(R.id.iv_header_bg);
        viewHolder.tv_header_name = (TextView) view.findViewById(R.id.tv_header_name);
        viewHolder.tv_num_name = (TextView) view.findViewById(R.id.tv_num_name);
        viewHolder.iv_share_use = (ImageView) view.findViewById(R.id.iv_share_use);
        viewHolder.iv_name_new = (ImageView) view.findViewById(R.id.iv_name_new);
        viewHolder.iv_lock_cover = (ImageView) view.findViewById(R.id.iv_lock_cover);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        String url = (mList.get(position)).getPic();
        //FIXME 其实完全没有必要这样，直接服务器下发全部图片就完事儿了呗。
        RequestOptions options = new RequestOptions();
        options.transform(new GlideCornerTransform(mContext,8)).placeholder(R.drawable.icon_iv_fail).dontAnimate();
        if(mList!=null && position == mList.size()-1 && "全部".equals(mList.get(position).getName())){
            Glide.with(mContext).load(R.drawable.icon_all).apply(options).into(holder.iv_header_bg);
        }else{
            Glide.with(mContext).load(TextUtils.isEmpty(url) ? R.drawable.icon_all : url).apply(options).into(holder.iv_header_bg);
        }
        if ("全部".equals(mList.get(position).getName())){
            holder.tv_header_name.setText("更多播单");
            holder.tv_header_name.setTextColor(ContextCompat.getColor(mContext,R.color.color_2ba7ff));
            holder.tv_num_name.setBackgroundResource(R.color.color_00000000);
        }else{
            holder.tv_header_name.setText((mList.get(position)).getName());
            holder.tv_header_name.setTextColor(ContextCompat.getColor(mContext,R.color.color_333));
            holder.tv_num_name.setBackgroundResource(R.drawable.item_recommend_header_name);
        }
        String audio_num = mList.get(position).getAudio_num();
        if (TextUtils.isEmpty(audio_num)){
            holder.tv_num_name.setText("");
        }else{
            holder.tv_num_name.setText(audio_num+"条内容");
        }
        //解锁所用字段
        final String isShare = mList.get(position).getIs_share();
        String tagId = mList.get(position).getTag_id();
        final String isUnlocked = mList.get(position).getIs_unlocked();
        if ("1".equals(isShare) && "0".equals(isUnlocked)){
            holder.iv_share_use.setVisibility(View.VISIBLE);
        }else{
            holder.iv_share_use.setVisibility(View.GONE);
        }

        if ("1".equals(tagId)){
            holder.iv_name_new.setVisibility(View.VISIBLE);
        }else{
            holder.iv_name_new.setVisibility(View.GONE);
        }

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {

                if ("1".equals(isShare) && "0".equals(isUnlocked)){//未解锁
                    //如果有锁就去跳转分享
                    RecommendData.DataBean.PlayCoversBean.ShareBean share = mList.get(position).getShare();
                    PlaydeatalData.DataBean.ShareBean shareBean = new PlaydeatalData.DataBean.ShareBean();
                    shareBean.setDesc(share.getDesc());
                    shareBean.setH5_url(share.getH5_url());
                    shareBean.setPic_url(share.getPic_url());
                    shareBean.setTitle(share.getTitle());
                    new CustomBottomSheetDialogFragment(shareBean, new CustomBottomSheetDialogFragment.ShareCallBack() {
                        @Override
                        public void shareSuccess(boolean isSuccess) {
                            shareResult(isSuccess,mList.get(position).getId(),position);
                        }
                    },true).show(((FragmentActivity)mContext).getSupportFragmentManager(), "abc");
                    //分享后解锁的播单
                    MobclickAgent.onEvent(mContext.getApplicationContext(), MobClickHelper.DIS_BAG_LOCK,mList.get(position).getName());
                    HashMap<String,Object> temp = new HashMap<>();
                    temp.put("分享后解锁的播单",mList.get(position).getName().toString());
                    ZhugeSDK.getInstance().track(mContext.getApplicationContext(),MobClickHelper.DIS_BAG_LOCK,temp);
                    //未解锁
                    ClickLog.clickLog(ClickLog.dis_bag_lock,mList.get(position).getId(),mList.get(position).getId());
                }else{
                    if(position == mList.size()-1){

                        Intent intentList = new Intent(mContext, AllPlayerAcitivity.class);
                        if (TextUtils.isEmpty(category_id)){
                            category_id = "";
                        }
                        intentList.putExtra("category_id",category_id);
                        intentList.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        //所有播单入口
                        MobclickAgent.onEvent(mContext.getApplicationContext(), MobClickHelper.DIS_BAG_ALL);
                        ZhugeSDK.getInstance().track(mContext.getApplicationContext(),MobClickHelper.DIS_BAG_ALL);

                        mContext.startActivity(intentList);
                        //
                        ClickLog.clickLog(ClickLog.dis_bag_all,"0","0");
                    }else{
                        if (!TextUtils.isEmpty(mList.get(position).getId())){
                            Intent intentDetail = new Intent(mContext, PlayDeatalActivity.class);
                            intentDetail.putExtra(VoicePacketDBHelper.LIST_ID,mList.get(position).getId());
                            intentDetail.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                            if("1".equals(isShare) && "1".equals(isUnlocked)){
                                //已经分享解锁的播单
                                MobclickAgent.onEvent(mContext.getApplicationContext(), MobClickHelper.DIS_BAG_OPEN,mList.get(position).getName());
                                HashMap<String,Object> temp = new HashMap<>();
                                temp.put("已经分享解锁的播单",mList.get(position).getName().toString());
                                ZhugeSDK.getInstance().track(mContext.getApplicationContext(),MobClickHelper.DIS_BAG_OPEN,temp);
                                //
                                ClickLog.clickLog(ClickLog.dis_bag_open,mList.get(position).getId(),mList.get(position).getId());
                            }else{
                                //非分享后解锁的播单
                                MobclickAgent.onEvent(mContext.getApplicationContext(), MobClickHelper.DIS_BAG,mList.get(position).getName());
                                HashMap<String,Object> temp = new HashMap<>();
                                temp.put("非分享后解锁的播单",mList.get(position).getName().toString());
                                ZhugeSDK.getInstance().track(mContext.getApplicationContext(),MobClickHelper.DIS_BAG,temp);
                                //
                                ClickLog.clickLog(ClickLog.dis_bag,mList.get(position).getId(),mList.get(position).getId());
                            }
                            mContext.startActivity(intentDetail);

                        }
                    }

                }

                //分享后解锁的播单
                MobclickAgent.onEvent(mContext.getApplicationContext(), MobClickHelper.DIS_TAB,mList.get(position).getName());
                HashMap<String,Object> temp = new HashMap<>();
                temp.put("点击播单",mList.get(position).getName().toString());
                ZhugeSDK.getInstance().track(mContext.getApplicationContext(),MobClickHelper.DIS_TAB,temp);
                }catch (Exception e){

                }
            }
        });
    }

    private void shareResult(boolean isSuccess, final String id, final int position){
        if (isSuccess) {
            TreeMap<String,String> map = new TreeMap<>();
            map.put("audio_id",id);
            map.put("type","2");
            HttpClient.post(HttpConfig.SERVER + HttpConfig.SHARE, map, new com.warmlight.voicepacket.http.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, String response){
//                    String string = response.body().string();
                    ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(response);
                    if (listMapByJson.size()>0){
                        Map<String, String> map1 = listMapByJson.get(0);
                        if ("200".equals(map1.get("code"))){
                            EventBus.getDefault().post(new ShareUnlock(false,position,id));
//                            mList.get(position).setUnlockSuccess(true);
                        }
                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    public void setCategoryId(String category_id) {
        this.category_id = category_id;
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        public ViewHolder(View itemView) {
            super(itemView);
        }

        ImageView iv_header_bg;
        TextView tv_header_name;
        TextView tv_num_name;
        ImageView iv_share_use;
        ImageView iv_name_new;
        ImageView iv_lock_cover;
    }

    public void addList(List<RecommendData.DataBean.PlayCoversBean> list){
//        if(mList == null){
//            mList = new ArrayList<>();
//        }
        mList = list;
        notifyDataSetChanged();
    }

    public List<RecommendData.DataBean.PlayCoversBean> getList(){
        return mList;
    }
}
